
package br.ucb.cesbdao.servicos;


import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Time;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import br.ucb.cesbdao.beans.Acesso;
import br.ucb.cesbdao.controller.ControladorJanelas;
import br.ucb.cesbdao.enuns.EnumControleJanela;
import br.ucb.cesbdao.enuns.EnumPatternLayout;
import br.ucb.cesbdao.janelas.JanelaConexao;
import br.ucb.cesbdao.model.AtendimentoModel;
import br.ucb.cesbdao.model.NaoAgendadoModel;
import br.ucb.cesbdao.model.TrabalhadorModel;
import br.ucb.cesbdao.model.impl.AtendimentoModelImpl;
import br.ucb.cesbdao.model.impl.NaoAgendadoModelImpl;
import br.ucb.cesbdao.model.impl.TrabalhadorModelImpl;
import br.ucb.cesbdao.modeloTabelas.ModeloTabelaAtendenteApoio;
import br.ucb.cesbdao.modeloTabelas.ModeloTabelaAtendimentoApoio;
import br.ucb.cesbdao.persistencia.dao.AcessoDAO;
import br.ucb.cesbdao.persistencia.factory.FactoryConnection;
import br.ucb.cesbdao.visao.Visao;

public class Servicos {

	static Logger logger = Logger.getLogger(Servicos.class);

	public static void encerraPrograma(int tempo)  {
		try { 
			Thread.sleep(tempo * 1000);
		} catch (InterruptedException e) { 
			logger.error(e.getMessage());
		}
	}

	public static String splitBusca(String string)  {
		return (string.split(" "))[0];
	}

	public static String unFormat(String str)  {
		return str.replace(".", "").replace("-", "").replace(" ", "").replace("/", "").replace(")", "").replace("(", "");
	}

	public static Integer[] parseInteger(String arrayString[]){
		Integer arrayInteger[] = new Integer[arrayString.length];
		for(int i = 0; i < arrayString.length; i++){
			try{
				arrayInteger[i] = Integer.parseInt(arrayString[i]);
			}catch(NumberFormatException ex){
				return null;
			}
		}
		return arrayInteger;
	}

	public static String verificaEntrada(JCheckBox checkEntrada) {
		if(checkEntrada.isSelected())
			return TimeUtil.getHoraSys();
		return null;
	}

	public static Integer verificaCodSocio(String campCodSocio) {
		Integer cod = null;
		try {
			cod = Integer.parseInt(campCodSocio);
		} catch (NumberFormatException e) {
			return 0;
		}
		return cod;
	}

	public static void limpaCadastraAtendido(JTextField txtNome, ButtonGroup btGrupSexo) {
		txtNome.setText("");
		btGrupSexo.clearSelection();
	}

	public static void proxSenha(JLabel lblNproxSenha, ModeloTabelaAtendimentoApoio modeloTabelaAtendimento) {
		lblNproxSenha.setText(modeloTabelaAtendimento.getSenha());
	}
	public static void proxSenhaP(JLabel lblNproxSenha, ModeloTabelaAtendimentoApoio modeloTabelaAtendimento) {
		lblNproxSenha.setText(modeloTabelaAtendimento.getSenhaP());

	}
	public static void proxSenhaE(JLabel lblNproxSenha, ModeloTabelaAtendimentoApoio modeloTabelaAtendimento) {
		lblNproxSenha.setText(modeloTabelaAtendimento.getSenhaE());

	}
	public static void proxSenhaEs(JLabel lblNproxSenha, ModeloTabelaAtendimentoApoio modeloTabelaAtendimento) {
		lblNproxSenha.setText(modeloTabelaAtendimento.getSenhaEs());

	}
	public static void preencheCabecario(JLabel lblQtdafis,
			JLabel lblQtdRestam,
			JLabel lblNproxSenha,
			JLabel lblNproxSenhaP,
			ModeloTabelaAtendimentoApoio modeloTabelaAtendimento,
			ModeloTabelaAtendenteApoio modeloTabelaTrabalhador,
			JLabel lblNproxSenhaE,
			JLabel lblNproxSenhaEs,
			JLabel lblN_agn
			){
		
		TrabalhadorModel trabModel = new TrabalhadorModelImpl();
		AtendimentoModel atendModel = new AtendimentoModelImpl();
		NaoAgendadoModel nAgenModel = new NaoAgendadoModelImpl();
		trabModel.qntAfisAtendimento(lblQtdafis,modeloTabelaTrabalhador);
		atendModel.qtdRestam(lblQtdRestam);
		proxSenha(lblNproxSenha,modeloTabelaAtendimento);
		proxSenhaP(lblNproxSenhaP,modeloTabelaAtendimento);
		proxSenhaE(lblNproxSenhaE,modeloTabelaAtendimento);
		proxSenhaEs(lblNproxSenhaEs,modeloTabelaAtendimento);
		lblN_agn.setText(nAgenModel.qtdNaoAgendado());
	}

	public static Time verificaHora(String horarioChegada) {
		if(horarioChegada == null || horarioChegada.charAt(0) == ' ')
			return null;
		return Time.valueOf(horarioChegada+":00");
	}

	public static String tipoDeAcesso(String tipoDeTrabalhador) {
		if(tipoDeTrabalhador.equalsIgnoreCase("F")){
			return "F";
		}
		else
			return "A";
	}

	public static String getString(String msg, String titulo, String descricao) {
		String string =null;
		do{
			string = Visao.getString(msg, titulo, descricao);
			if(string == null)
				return null;
		}while(!Validadores.validaString(string));

		return string;
	}
	public static String getString(String msg, String titulo) {
		String string =null;
		do{
			string = Visao.getString(msg, titulo);
			if(string == null)
				return null;
		}while(!Validadores.validaString(string));
		return string;
	}


	/*
	 * Codigo pronto da net para verificar força da senha
	 * http://javafree.uol.com.br/topic-882085-Ajuda-Com-codigo-Java-no-Eclipse.html
	 */
	public static boolean CheckPasswordStrength(String passwd, JLabel lblforcaSenha) {  
		String PASSWORD_MIXED_CASE = "1";  
		String PASSWORD_MIN_LENGTH = "6";  
		String PASSWORD_MAX_LENGTH = "30";  
		String PASSWORD_NUMERIC = "1";  
		String PASSWORD_SPECIAL = "1";  
		String PASSWORD_STRENGTH = "30";

		int upper = 0, lower = 0, numbers = 0, special = 0, length = 0;  
		int intScore = 0;  
		String strVerdict = "none", strLog = "";  
		Pattern p;  
		Matcher m;  
		if (passwd == null)  
			return false;  
		// PASSWORD LENGTH  
		length = passwd.length();  
		if (length < 5) // length 4 or less  
		{  
			intScore = (intScore + 3);  
			strLog = strLog + "3 points for length (" + length + ")\n";  
		} else if (length > 4 && passwd.length() > 5) // length between 5 and 7  
		{  
			intScore = (intScore + 6);  
			strLog = strLog + "6 points for length (" + length + ")\n";  
		} else if (  
				length > 7 && passwd.length() < 16) // length between 8 and 15  
		{  
			intScore = (intScore + 12);  
			strLog = strLog + "12 points for length (" + length + ")\n";  
		} else if (length > 15) // length 16 or more  
		{  
			intScore = (intScore + 1);  
			strLog = strLog + "18 point for length (" + length + ")\n";  
		}  
		// LETTERS   
		p = Pattern.compile(".??[a-z]");  
		m = p.matcher(passwd);  
		while (m.find()) // [verified] at least one lower case letter  
		{  
			lower += 1;  
		}  
		if (lower > 0) {  
			intScore = (intScore + 1);  
			strLog = strLog + "1 point for a lower case character\n";  
		}  
		p = Pattern.compile(".??[A-Z]");  
		m = p.matcher(passwd);  
		while (m.find()) // [verified] at least one upper case letter  
		{  
			upper += 1;  
		}  
		if (upper > 0) {  
			intScore = (intScore + 5);  
			strLog = strLog + "5 point for an upper case character\n";  
		}  
		// NUMBERS  
		p = Pattern.compile(".??[0-9]");  
		m = p.matcher(passwd);  
		while (m.find()) // [verified] at least one number  
		{  
			numbers += 1;  
		}  
		if (numbers > 0) {  
			intScore = (intScore + 5);  
			strLog = strLog + "5 points for a number\n";  
			if (numbers > 1) {  
				intScore = (intScore + 2);  
				strLog = strLog + "2 points for at least two numbers\n";  
				if (numbers > 2) {  
					intScore = (intScore + 3);  
					strLog = strLog + "3 points for at least three numbers\n";  
				}  
			}  
		}  
		// SPECIAL CHAR  
		p = Pattern.compile(".??[:,!,@,#,$,%,^,&,*,?,_,~]");  
		m = p.matcher(passwd);  
		while (m.find()) // [verified] at least one special character  
		{  
			special += 1;  
		}  
		if (special > 0) {  
			intScore = (intScore + 5);  
			strLog = strLog + "5 points for a special character\n";  
			if (special > 1) {  
				intScore += (intScore + 5);  
				strLog =  
						strLog + "5 points for at least two special characters\n";  
			}  
		}  
		// COMBOS  
		if (upper > 0 && lower > 0) // [verified] both upper and lower case  
		{  
			intScore = (intScore + 2);  
			strLog = strLog + "2 combo points for upper and lower letters\n";  
		}  
		if ((upper > 0 || lower > 0)  
				&& numbers > 0) // [verified] both letters and numbers  
		{  
			intScore = (intScore + 2);  
			strLog = strLog + "2 combo points for letters and numbers\n";  
		}  
		if ((upper > 0 || lower > 0)  
				&& numbers > 0  
				&& special > 0) // [verified] letters, numbers, and special characters  
		{  
			intScore = (intScore + 2);  
			strLog =  
					strLog  
					+ "2 combo points for letters, numbers and special chars\n";  
		}  
		if (upper > 0 && lower > 0 && numbers > 0 && special > 0)           // [verified] upper, lower, numbers, and special characters  
		{  
			intScore = (intScore + 2);  
			strLog =  
					strLog  
					+ "2 combo points for upper and lower case letters, numbers and special chars\n";  
		}  
		if (intScore < 16) {  
			strVerdict = "Muito Fraca";
			lblforcaSenha.setText(strVerdict);
			lblforcaSenha.setForeground(new Color(255, 0, 0));
		} else if (intScore > 15 && intScore < 25) {  
			strVerdict = "Fraca";
			lblforcaSenha.setText(strVerdict);
			lblforcaSenha.setForeground(new Color(205, 102,0));  
		} else if (intScore > 24 && intScore < 35) {  
			strVerdict = "Media";
			lblforcaSenha.setText(strVerdict);
			lblforcaSenha.setForeground(new Color(255,255, 0));
		} else if (intScore > 34 && intScore < 45) {  
			strVerdict = "Forte";
			lblforcaSenha.setText(strVerdict);
			lblforcaSenha.setForeground(new Color(204,255,51));
		} else {  
			strVerdict = "Muito Forte";
			lblforcaSenha.setText(strVerdict);
			lblforcaSenha.setForeground(new Color(0,255, 0));  
		}  


		// Does it meet the password policy?  
		try {  
			int min = Integer.parseInt(PASSWORD_MIN_LENGTH);  
			if (length < min)  
				return false;  
		} catch (Exception e) {  
			;  
		} // undefined  
		try {  
			int max = Integer.parseInt(PASSWORD_MAX_LENGTH);  
			if (length > max)  
				return false;  
		} catch (Exception e) {  
			;  
		} // undefined  
		try {  
			int num = Integer.parseInt(PASSWORD_NUMERIC);  
			if (numbers < num)  
				return false;  
		} catch (Exception e) {  
			;  
		} // undefined  
		try {  
			int mix = Integer.parseInt(PASSWORD_MIXED_CASE);  
			if (upper < mix || lower < mix)  
				return false;  
		} catch (Exception e) {  
			;  
		} // undefined  
		try {  
			int str = Integer.parseInt(PASSWORD_STRENGTH);  
			if (intScore < str)  
				return false;  
		} catch (Exception e) {  
			;  
		} // undefined  
		try {  
			int spec = Integer.parseInt(PASSWORD_SPECIAL);  
			if (special < spec)  
				return false;  
		} catch (Exception e) {  
			;  
		} // undefined  
		return true;  
	}

	@SuppressWarnings("deprecation")
	public static boolean verificaOldSenha(JPasswordField txtOldSenha,
			Acesso acesso) {
		if(txtOldSenha.getText() == null || txtOldSenha.getText().isEmpty() || !acesso.getSenha().equals(EncriptaSenha.encripta(txtOldSenha.getText())))
			return false;
		return true;
	}

	public static boolean verificaSenhaIgual(String newSenha, String confSenha) {
		if(newSenha == null || newSenha.isEmpty() || confSenha == null || confSenha.isEmpty() || !newSenha.equals(confSenha))
			return false;
		return true;
	}

	public static boolean validaSenha(String senha) {
		if(senha.length() > 30 || senha.length()  < 6)
			return false;
		return true;
	}

	public static void verificaBancoAcesso() {
		Connection con = null;
		try {
			con = FactoryConnection.getInstance().criaConexaoFirst();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (SQLException e) {
			ControladorJanelas.invokeJDialog("Login", EnumControleJanela.DIALOG_FIRST_CONNECT.getNomeJanela());
		}
		if(con != null){
			JanelaConexao janConexao = new JanelaConexao();
			janConexao.addWindowListener(new WindowAdapter() { 
				public void windowClosing(WindowEvent evJanela) {
					logger.info("Encerrando a aplicação.");
					System.exit(0);
				}
			});
		}
	}
	public static void verificaBanco() {
		if(FactoryConnection.getInstance().criaConexao() == null){
			if(Visao.showYesNo("Banco de dados do sistema não encontrado \n  Deseja ","AVISO"))
				criaBanco();
		}
	}
	public static void criaBanco(){
		AcessoDAO dao = new AcessoDAO(FactoryConnection.getInstance().criaConexao());
		FileReader fr;
		BufferedReader br;
		StringBuffer sb = new StringBuffer();
		try {
			fr = new FileReader("banco.sql");
			br = new BufferedReader(fr);
			while(br.ready())
				sb.append(br.readLine());
			String[] sql = sb.toString().split(";");
			br.close();
			dao.criaBanco(sql);
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (SQLException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}

	public static void salvaSenhaBanco(String user, String senha) throws IOException {
		Properties prop = new Properties();
		try {
			InputStream leitura = new FileInputStream("conexao.properties");
			prop.load(leitura);
			leitura.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		// seta o novo cadastro
		prop.setProperty("USUARIO",user);
		prop.setProperty("SENHA",senha);
		FileOutputStream arquivo = new FileOutputStream("conexao.properties");
		// salva no arquivo
		prop.store(arquivo, "Arquivo de Propriedades");
		arquivo.close();
		ResourceBundleUtil.refresh();
	}

	public static boolean isAdmFirst(String cpfMask) {
		String cpf = cpfMask.replace(".","").replace("-","").replace(" ","");
		if(cpf == "00000000000")
			return true;
		else
			return false;
	}

	public static String getNomeLog() {
		return "log"+DateUtil.getDataSemSeparadores(new Date())+".log";
	}

	/**
	 * Dois tipos de retorno, o primeiro grava dentro da aplicação.
	 * O segundo grava o log no disco local C.
	 */
	private static Appender initAppender() {
		try {
			return new FileAppender(new PatternLayout(EnumPatternLayout.LAYOUT_COMPLETO.getLayout()), "logs/"+Servicos.getNomeLog());
//			return new FileAppender(new PatternLayout(EnumPatternLayout.LAYOUT_DATA_HORA_PRIORIDADE.getLayout()), "/logsCesb/"+Servicos.getNomeLog());
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	public static Logger carregaLog(Class classe) {
		Logger log = Logger.getLogger(classe);
		log.addAppender(initAppender());
		return log;
		
	}

	public static boolean verificaSenhaLogin(String senhaBanco, String senhaTela) {
		return senhaBanco.equals(EncriptaSenha.encripta(senhaTela));
	}
	public static String stringNumberOfCPF(String cpfFormatado){
		String cpf = cpfFormatado.replace(".","").replace("-","").replace(" ","");
		return cpf;
	}

}